<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="角色名称" prop="roleNameLike">
        <el-input
          v-model="queryParams.roleNameLike"
          placeholder="请输入角色名称"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKeyLike">
        <el-input
          v-model="queryParams.roleKeyLike"
          placeholder="请输入权限字符"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          size="default"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="default"
          style="width: 240px"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" :perm="['system:role:search']" />
        <reset-button @click="resetQuery" :perm="['system:role:search']" />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" :perm="['system:role:insert']" :roleType="['conf']" />
      <delete-button
        @click="handleDelete"
        :disabled="multiple"
        :perm="['system:role:delete']"
        :roleType="['conf']"
      />
      <export-button @click="handleExport" :perm="['system:role:export']" />
      <right-toolbar
        v-model:showSearch="showSearch"
        @query-table="getList"
        :perm="['system:role:search']"
      />
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="角色ID" prop="roleId" align="center" min-width="100" />
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" />
      <el-table-column label="角色类型" prop="roleType" align="center" min-width="100">
        <template #default="scope">
          <el-tooltip
            v-if="scope.row.roleType === '0'"
            content="【系统内置】授权后可拥有所有菜单所有按钮权限"
            placement="right-start"
            effect="light"
          >
            <el-tag type="danger">超级角色</el-tag>
          </el-tooltip>
          <el-tooltip v-else-if="scope.row.roleType === '1'" placement="right-start" effect="light">
            <template #content>
              <div>
                【系统内置】只有配置类型角色授权后才可以做系统的配置管理<br />配置管理包括角色、菜单、字典、参数和ZCache等管理权限
              </div>
            </template>
            <el-tag type="warning">配置角色</el-tag>
          </el-tooltip>
          <el-tooltip v-else-if="scope.row.roleType === '2'" placement="right-start" effect="light">
            <template #content>
              <div>
                用于实际业务系统的功能应用操作<br />即使进行菜单按钮授权也无法操作以上配置管理功能
              </div>
            </template>
            <el-tag type="success" effect="light">应用角色</el-tag>
          </el-tooltip>
          <el-tag v-else>{{ scope.row.roleType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="权限字符" prop="roleKey" align="center" min-width="200" />
      <el-table-column label="显示顺序" prop="roleSort" align="center" min-width="100" />
      <el-table-column label="状态" align="center" min-width="160">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            v-if="hasRoleType(['conf'])"
            active-value="Y"
            inactive-value="N"
            @change="handleStatusChange(scope.row)"
            active-text="启用"
            inactive-text="禁用"
          />
          <span v-else>{{ selectDictLabel(statusOptions, scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="160" />
      <el-table-column
        label="操作"
        align="center"
        min-width="220"
        class-name="small-padding fixed-width"
        v-if="hasRoleType(['conf'])"
      >
        <template #default="scope">
          <el-button
            size="default"
            type="primary"
            link
            icon="CircleCheck"
            @click="handleDataScope(scope.row)"
            v-hasRoleType="['conf']"
            v-hasPermi="['system:role:update']"
          >数据权限</el-button>
          <TextDetailButton
            @click="handleView(scope.row)"
            :perm="['system:role:search']"
            :roleType="['conf']"
            text="用户清单"
          ></TextDetailButton>
          <text-edit-button
            @click="handleUpdate(scope.row)"
            :perm="['system:role:update']"
            :roleType="['conf']"
          />
          <text-delete-button
            @click="handleDelete(scope.row)"
            :perm="['system:role:delete']"
            :roleType="['conf']"
            :title="'是否确认删除' + scope.row.roleName + '?'"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="open"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色类型">
          <el-tooltip placement="right-start" effect="light">
            <template #content>
              <div>超级角色和配置角色只能通过系统内置，不支持通过页面添加</div>
            </template>
            <el-tag type="success" effect="light">应用角色</el-tag>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number
            v-model="form.roleSort"
            controls-position="right"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :value="dict.dictValue">{{
              dict.dictLabel
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" />
      </template>
    </drag-dialog>

    <!-- 分配角色数据权限对话框 -->
    <drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="openDataScope"
      width="600px"
      append-to-body
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="角色名称">
          <el-input v-model="form.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="form.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope" style="width: 100%">
            <el-option
              v-for="dict in dataScopeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授权的公司" v-show="form.dataScope === '2'">
          <el-tree
            :data="companyOptions"
            show-checkbox
            default-expand-all
            ref="company"
            node-key="id"
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="授权部门" v-show="form.dataScope === '3'">
          <el-tree
            :data="orgOptions"
            show-checkbox
            default-expand-all
            ref="org"
            node-key="id"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitDataScope" @cancel="cancelDataScope" />
      </template>
    </drag-dialog>

    <!-- 用户列表 -->
    <drag-dialog
      title="用户列表"
      v-if="openUser"
      :close-on-click-modal="false"
      v-model="userList"
      width="1000px"
      append-to-body
      @close="closeUser"
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="登录账号" prop="loginName">
          <el-input
            v-model="queryUserListParams.loginName"
            placeholder="请输入要查询的登录名"
            clearable
            size="default"
            style="width: 240px"
            @keyup.enter="handleQueryUser"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryUserListParams.userName"
            placeholder="请输入用户名称"
            clearable
            size="default"
            style="width: 240px"
            @keyup.enter="handleQueryUser"
          />
        </el-form-item>
        <el-form-item>
          <search-button @click="handleQueryUser" :perm="['system:user:search']" />
          <reset-button @click="resetQueryUser" :perm="['system:user:search']" />
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="userList">
        <el-table-column label="用户ID" min-width="120" align="center" prop="userId" />
        <el-table-column
          label="登录账号"
          min-width="160"
          align="center"
          prop="loginName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="用户名称"
          min-width="160"
          align="center"
          prop="userName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="公司/部门"
          min-width="180"
          align="center"
          prop="companyName"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            {{ (scope.row.companyName || '-') + ' / ' + (scope.row.deptName || '-') }}
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center" prop="phonenumber" width="130" />
        <el-table-column label="邮箱" align="center" prop="email" width="160" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-popover
              v-if="scope.row.status === '2'"
              placement="top-start"
              width="240"
              trigger="hover"
              title="用户已锁定"
              :content="showUserStatusText(scope)"
            >
              <template #reference>
                <el-tag type="warning">锁定</el-tag>
              </template>
            </el-popover>
            <el-tag
              v-else
              :type="scope.row.status === '0' ? 'success' : 'danger'"
              disable-transitions
            >{{ scope.row.status === '0' ? '正常' : '禁用' }}</el-tag
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="userTotal > 0"
        :total="userTotal"
        v-model:page="queryUserListParams.pageNum"
        v-model:limit="queryUserListParams.pageSize"
        @pagination="handleView"
      />
    </drag-dialog>
  </div>
</template>

<script>
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  dataScope,
  checkRoleNameyUnique,
  checkRoleKeyUnique,
  changeRoleStatus,
  roleDeptTreeselect,
  roleCompanyTreeselect,
  listUserByRoleId
} from '@base/api/base/role'
import { getTreeSelect as menuTreeselect, roleMenuTreeselect } from '@base/api/base/menu'

export default {
  name: 'SystemRole',
  data() {
    const checkRoleNameyUniqueRule = (rule, value, callback) => {
      checkRoleNameyUnique(value, this.form.roleId).then((response) => {
        if (response.data === true) {
          callback('角色名称已存在')
        } else {
          callback()
        }
      })
    }
    const checkRoleKeyUniqueRule = (rule, value, callback) => {
      checkRoleKeyUnique(value, this.form.roleId).then((response) => {
        if (response.data === true) {
          callback('角色权限已存在')
        } else {
          callback()
        }
      })
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 数据范围选项
      dataScopeOptions: [],
      // 菜单列表
      menuOptions: [],
      // 组织机构列表，包含公司和部门
      orgOptions: [],
      // 公司列表
      companyOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        delFlag: 'N',
        orderBy: 'ROLE_SORT',
        roleNameLike: undefined,
        roleKeyLike: undefined,
        status: undefined
      },
      // 用户查询参数
      queryUserListParams: {
        pageNum: 1,
        pageSize: 10,
        roleId: undefined
      },
      // 用户总数
      userTotal: 0,
      // 用户表格数据
      userList: [],
      // 是否打开用户窗口
      openUser: false,
      // 角色id
      roleId: undefined,
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { required: true, validator: checkRoleNameyUniqueRule, trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '权限字符不能为空', trigger: 'blur' },
          { required: true, validator: checkRoleKeyUniqueRule, trigger: 'blur' }
        ],
        roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_data_scope').then((response) => {
      this.dataScopeOptions = response.data
    })
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true
      listRole(
        this.addDateRange(this.queryParams, ['createTimeStart', 'createTimeEnd'], this.dateRange)
      ).then((response) => {
        this.roleList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getHalfCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 所有机构节点数据
    getOrgAllCheckedKeys() {
      // 判断是自定义公司还是自定义部门
      const orgRef = this.form.dataScope === '2' ? this.$refs.company : this.$refs.org
      return orgRef.getCheckedKeys(true)
      // // 目前被选中的机构节点
      // let checkedKeys = orgRef.getHalfCheckedKeys();
      // // 半选中的机构节点
      // let halfCheckedKeys = orgRef.getCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      // return checkedKeys;
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then((response) => {
        this.menuOptions = response.data.menus
        return response
      })
    },
    /** 根据角色ID查询机构树结构 */
    getRoleDeptTreeselect(roleId) {
      return roleDeptTreeselect(roleId).then((response) => {
        this.orgOptions = response.data.orgs
        return response
      })
    },
    /** 根据角色ID查询机构树结构 */
    getRoleCompanyTreeselect(roleId) {
      return roleCompanyTreeselect(roleId).then((response) => {
        this.companyOptions = response.data.companys
        return response
      })
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === 'Y' ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.roleName + '"角色吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          return changeRoleStatus(row.roleId, row.status)
        })
        .then(() => {
          this.msgSuccess(text + '成功')
        })
        .catch(function () {
          row.status = row.status === 'Y' ? 'N' : 'Y'
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: 'Y',
        menuIds: [],
        scopes: [],
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getMenuTreeselect()
      this.open = true
      this.title = '添加角色'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const roleId = row.roleId || this.ids[0]
      const roleMenu = this.getRoleMenuTreeselect(roleId)
      getRole(roleId).then((response) => {
        this.form = response.data
        this.open = true
        this.$nextTick(() => {
          roleMenu.then((res) => {
            this.$refs.menu.setCheckedKeys(res.data.checkedKeys)
          })
        })
        this.title = '修改角色'
      })
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset()
      const roleDeptTreeselect = this.getRoleDeptTreeselect(row.roleId)
      const roleCompanyTreeselect = this.getRoleCompanyTreeselect(row.roleId)
      getRole(row.roleId).then((response) => {
        this.form = response.data
        this.openDataScope = true
        this.$nextTick(() => {
          roleDeptTreeselect.then((res) => {
            this.$refs.org.setCheckedKeys(res.data.checkedKeys)
          })
          roleCompanyTreeselect.then((res) => {
            this.$refs.company.setCheckedKeys(res.data.checkedKeys)
          })
        })
        this.title = '分配数据权限'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            updateRole(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            addRole(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function () {
      if (this.form.roleId != undefined) {
        if (this.form.dataScope === '2' || this.form.dataScope === '3') {
          this.form.scopes = this.getOrgAllCheckedKeys()
        } else {
          this.form.scopes = []
        }
        dataScope(this.form).then((response) => {
          if (response.data === 1) {
            this.msgSuccess('修改成功')
            this.openDataScope = false
            this.getList()
          }
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = (row && row.roleId) || this.ids.join(',')
      delRole(roleIds)
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function () {})
    },
    /** 导出按钮操作 */
    handleExport: function () {
      // const queryParams = this.queryParams;
      // this.$confirm('是否确认导出所有角色数据项?', "警告", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(() => {
      this.downloadUrl(
        '/system/role/export',
        this.addDateRange(this.queryParams, ['createTimeStart', 'createTimeEnd'], this.dateRange)
      )
      // }).catch(e => {
      //   console.log(e);
      // });
    },
    /** 查询用户清单 */
    handleView: function (row) {
      this.roleId = row.roleId
      this.queryUserListParams.roleId = row.roleId
      listUserByRoleId(this.queryUserListParams).then(
        (response) => {
          this.userList = response.data.list
          this.userTotal = response.data.total
          this.openUser = true
        }
      )
    },
    /** 关闭用户列表 */
    closeUser() {
      this.openUser = false
      this.queryUserListParams = {
        pageNum: 1,
        pageSize: 10,
        loginName: undefined,
        userName: undefined,
        roleId: undefined
      }
      this.roleId = undefined
      this.userList = []
      this.userTotal = 0
    },
    /** 查询用户 */
    handleQueryUser(){
      listUserByRoleId(this.queryUserListParams).then(
        (response) => {
          this.userList = response.data.list
          this.userTotal = response.data.total
          this.openUser = true
        }
      )
    },
    /** 重置用户查询条件 */
    resetQueryUser(){
      this.queryUserListParams = {
        pageNum: 1,
        pageSize: 10,
        loginName: undefined,
        userName: undefined,
        roleId: this.roleId
      }
      this.handleQueryUser()
    }
  }
}
</script>
